
export type WaterfallOpts = {
    [key: string]: any;
    el?: string | HTMLElement;
    column?: number;
    gap?: number;
}

class Waterfall {
    private el: HTMLElement | null = null;
    private opts: WaterfallOpts = {};
    private items: HTMLCollection | null = null;
    private column: number = 4;
    private gap: number = 10;
    private itemWidth: number = 0;
    private miniHeightList: number[] = [];
    private miniIndex: number = 0;

    constructor(opts: WaterfallOpts) {
        this.opts = opts;
        this._init();
    }

    _init() {
        this.el = typeof this.opts.el === 'string' ? document.querySelector(this.opts.el) : this.opts.el;
        this.items = this.el?.children;
        this.column = this.opts.column;
        this.gap = this.opts.gap;
        this.itemWidth = (this.el?.offsetWidth - this.gap * 3) / this.column;
        this._render();
    }

    _render() {
        [...this.items].forEach((item: HTMLElement, index: number) => {
            if (index < this.column) {
                item.style.top = 0 + 'px';
                item.style.left = (this.itemWidth + this.gap) * index + 'px';
                this.miniHeightList.push(item.offsetHeight);
                
            }else{
                this.miniIndex = this._getMinIndex();
                item.style.top = this.miniHeightList[this.miniIndex] + this.gap + 'px';
                item.style.left = (this.itemWidth + this.gap) * this.miniIndex + 'px';
                this.miniHeightList[this.miniIndex] = this.miniHeightList[this.miniIndex] + this.gap + item.offsetHeight;
            }
        })
    }
    _getMinIndex() {
        return this.miniHeightList.indexOf(Math.min(...this.miniHeightList));
    }
}


export default Waterfall;

